package gov.pr.celepar.sentinela.mail;

import gov.pr.celepar.sentinela.dao.ParametrosDAO;
import gov.pr.celepar.sentinela.dao.factory.DAOFactory;
import gov.pr.celepar.sentinela.pojo.Parametros;
import gov.pr.celepar.sentinela.util.Criptografia;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SentinelaMail {

	public String substituirFrase(int param, String texto, String valor) {

		return texto.replaceAll("%" + param, valor);
	}

	public void enviarMailSimples(String server, String subject, String to, String from, String mensagem) throws AddressException, MessagingException {
		ParametrosDAO paramDao = DAOFactory.getDAOFactory().getParametrosDAO();
		Parametros parametrosSentinela;
		try {
			parametrosSentinela = paramDao.getParametros();
			final String username = parametrosSentinela.getMailOrigem();
			final String password = Criptografia.descriptografarBase(parametrosSentinela.getSenhaMailOrigem());
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");	
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", server);
			props.put("mail.smtp.port", "587");
			Session session = Session.getInstance(props, new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
			InternetAddress destinatario = new InternetAddress(to);
			InternetAddress remetente = new InternetAddress(from);
	
			Message message = new MimeMessage(session);
	
			message.setFrom(remetente);
			message.setRecipient(Message.RecipientType.TO, destinatario);
			message.setSubject(subject);
			message.setContent(mensagem.toString(), "text/plain");
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}